package cn.edu.qfnu.oj.web.controller;

import cn.edu.qfnu.oj.entity.Contest;
import cn.edu.qfnu.oj.entity.Problem;
import cn.edu.qfnu.oj.entity.Teacher;
import cn.edu.qfnu.oj.service.ContestService;
import cn.edu.qfnu.oj.service.ProblemService;
import cn.edu.qfnu.oj.service.TeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping(value = "contest/")
public class ContestController {

    private static final Logger log = LoggerFactory.getLogger(ContestController.class);

    private final ContestService contestService;
    private final TeacherService teacherService;
    private final ProblemService problemService;

    @Autowired
    public ContestController(ContestService contestService, TeacherService teacherService, ProblemService problemService) {
        this.contestService = contestService;
        this.teacherService = teacherService;
        this.problemService = problemService;
    }

    @RequestMapping(value = "index2", method = RequestMethod.GET)
    public String createTask() {
        return "task";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> crateContest(String title, String content,
                                         String start, String duration,
                                         List<Problem> problems, String teacherId) {
        
        Map<String, String> jsonMap = new HashMap<>();
        try {
            //从字符串中获取开始时间
            LocalDateTime startTime = LocalDateTime.parse(start);
            //比赛的持续时间duration：单位小时
            //结束时间通过开始时间与结束时间相加
            LocalDateTime endTime = startTime.plusHours(Long.parseLong(duration));

            //创建新任务
            Contest contest = new Contest(content, startTime, endTime, title);
            //通过遍历获得json中的problem_id
            for (Problem problem : problems) {
                //通过ID找到Problem
                Problem find = problemService.findById(problem.getId());
                //Problem加入题集
                find.getContests().add(contest);
                //更新题目记录
                problemService.saveOrUpdate(find);
                //题目集加入题目
                contest.getProblems().add(find);
                log.info("题目：" + find.getTitle() + "加入到比赛中");
            }
            Teacher teacher = teacherService.findById(teacherId);
            teacher.getContests().add(contest);
            teacherService.saveOrUpdate(teacher);
            //最后保存题目集
            contest.setTeacher(teacher);
            contestService.save(contest);
            jsonMap.put("result", "success");
            log.info("创建了一个新比赛: " + contest.getTitle());
        } catch (Exception e) {
            jsonMap.put("result", "error");
            log.error("创建比赛时出错", e);
        }
        return jsonMap;
    }

    @RequestMapping(value = "index3", method = RequestMethod.GET)
    public String modifyTask() {
        return "moTask";
    }

    @RequestMapping(value = "modify", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> modifyTask(Integer id, String title, String content,
                                          String start, String duration,
                                          @RequestBody Set<Problem> problems) {

        Map<String, String> jsonMap = new HashMap<>();

        try {
            Contest contest = contestService.findById(id);
            contestService.modify(contest, title, content, start, duration, problems);
            contestService.merge(contest);

            jsonMap.put("result", "success");
            log.info("修改了比赛: " + contest.getId() + " " + contest.getTitle());
        } catch (Exception e) {
            jsonMap.put("result", "error");
            log.error("修改比赛时出错", e);
        }
        return jsonMap;
    }

    @RequestMapping(value = "index5", method = RequestMethod.GET)
    public String delete() {
        return "deleteContest";
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(Integer id) {
        Map<String, String> jsonMap = new HashMap<>();

        try {
            contestService.removeById(id);
            jsonMap.put("result", "success");
            log.info("删除了比赛: " + id);
        } catch (Exception e) {
            jsonMap.put("result", "error");
            log.error("删除比赛时出错", e);
        }
        return jsonMap;
    }
}
